<template>
  <div class="deepseek-chat-container">
    <div class="chat-wrapper">
      <div class="chat-header">
        <h2>与 DeepSeek AI 对话</h2>
      </div>
      
      <div class="chat-history" ref="chatHistoryRef">
        <div v-for="(msg, index) in conversation" :key="index" :class="['message', msg.sender]">
          <el-avatar class="avatar" :size="32" :src="msg.sender === 'user' ? userAvatarUrl : deepseekAvatarUrl"></el-avatar>
          <div class="message-content">
             <pre class="text">{{ msg.text }}</pre>
          </div>
        </div>
        <div v-if="isLoading" class="message ai">
          <el-avatar class="avatar" :size="32" :src="deepseekAvatarUrl"></el-avatar>
          <div class="message-content">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span> 正在思考中...</span>
          </div>
        </div>
      </div>
      
      <div class="chat-input-area">
        <div class="input-wrapper">
          <el-input
            v-model="newMessage"
            placeholder="请输入你想对 AI 说的话..."
            type="textarea"
            :rows="3"
            resize="none"
            @keydown.enter.prevent="sendMessage"
            class="chat-input"
          />
          <el-button 
            type="primary" 
            @click="sendMessage" 
            :disabled="!newMessage.trim() || isLoading"
            class="send-button"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router'; // 引入 useRouter
import { chatWithDeepSeek } from '@/services/deepseekService'; // 确保路径正确
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import defaultAvatar from '@/assets/default-avatar.png'; // 假设有一个默认头像
import deepseekAvatar from '@/assets/deepseek-logo.png'; // 假设有一个 DeepSeek 的 logo
import config from '@/config';

const store = useStore();
const router = useRouter(); // 获取 router 实例

const newMessage = ref('');
const conversation = ref([]); // 存储对话历史 { sender: 'user' | 'ai', text: string }
const isLoading = ref(false);
const chatHistoryRef = ref(null); // 用于滚动到底部

// 获取用户信息和头像
const userInfo = computed(() => store.getters.getUserInfo);
// 使用 config.js 中的方法获取完整 URL，并提供默认头像
const userAvatarUrl = computed(() => {
  return config.getFullResourceUrl(userInfo.value.avatarUrl) || defaultAvatar;
});
const deepseekAvatarUrl = ref(deepseekAvatar); // DeepSeek 的头像

/**
 * 滚动到聊天记录底部
 * 确保新消息能够被用户看到
 */
const scrollToBottom = () => {
  nextTick(() => {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight;
    }
  });
};

/**
 * 发送消息到AI
 * 处理用户输入，调用API，显示回复
 */
const sendMessage = async () => {
  const messageText = newMessage.value.trim();
  if (!messageText || isLoading.value) {
    return;
  }

  // 1. 将用户消息添加到对话历史
  conversation.value.push({ sender: 'user', text: messageText });
  const userMessage = messageText; // 保存用户消息，因为 newMessage 会被清空
  newMessage.value = ''; // 清空输入框
  scrollToBottom();

  // 2. 设置加载状态
  isLoading.value = true;

  // 3. 调用 API
  try {
    const response = await chatWithDeepSeek(userMessage);

    if (response.success) {
      // 4. 将 AI 回复添加到对话历史
      conversation.value.push({ sender: 'ai', text: response.data });
      scrollToBottom();
    } else {
      // API 调用本身是成功的，但业务逻辑失败（例如 token 失效已在 service 中处理并提示）
      // 如果错误不是 token 失效导致的（例如服务器内部错误），可能需要恢复用户输入
      if (!response.message.includes('认证失败')) {
         // 可以选择将用户未发送成功的消息恢复到输入框
         // newMessage.value = userMessage;
      } else {
         // 如果是token问题导致登出，跳转到登录页
         router.push('/login');
      }
    }
  } catch (error) {
    // 这个 catch 主要处理 chatWithDeepSeek 函数本身抛出的未捕获异常（理论上比较少见）
    console.error('发送消息时发生意外错误:', error);
    ElMessage.error('发送消息失败，请检查网络或稍后重试');
     // newMessage.value = userMessage; // 同样可以考虑恢复用户输入
  } finally {
    // 5. 取消加载状态
    isLoading.value = false;
  }
};

// 初始化时可以添加一条欢迎消息
onMounted(() => {
  conversation.value.push({ sender: 'ai', text: '你好！我是 DeepSeek AI，有什么可以帮助你的吗？' });
});

</script>

<style scoped>
/* 主容器：全屏布局 */
.deepseek-chat-container {
  height: calc(100vh - 60px); /* 减去header高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
}

/* 聊天包装器：固定尺寸的聊天界面 */
.chat-wrapper {
  width: 100%;
  max-width: 900px;
  height: 100%;
  max-height: 800px;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 聊天头部 */
.chat-header {
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
}

.chat-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

/* 聊天历史区域：可滚动的主要内容区 */
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 0; /* 重要：允许flex子项收缩 */
}

/* 自定义滚动条 */
.chat-history::-webkit-scrollbar {
  width: 6px;
}

.chat-history::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-history::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-history::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 消息样式 */
.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message.user .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 18px 18px 4px 18px;
  margin-right: 12px;
  order: -1;
}

.message.ai .message-content {
  background-color: #ffffff;
  color: #333;
  border-radius: 18px 18px 18px 4px;
  margin-left: 12px;
  border: 1px solid #e1e5e9;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.avatar {
  flex-shrink: 0;
  margin-top: 2px;
}

.message-content {
  padding: 12px 16px;
  max-width: 70%;
  word-wrap: break-word;
}

.text {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
  font-family: inherit;
}

/* 输入区域：固定在底部 */
.chat-input-area {
  padding: 20px 24px;
  background-color: #ffffff;
  border-top: 1px solid #e1e5e9;
  flex-shrink: 0; /* 防止输入区域被压缩 */
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
}

.chat-input {
  flex: 1;
}

.chat-input :deep(.el-textarea__inner) {
  border-radius: 20px;
  border: 2px solid #e1e5e9;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.4;
  resize: none;
  transition: border-color 0.2s ease;
}

.chat-input :deep(.el-textarea__inner):focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.send-button {
  height: 54px;
  min-width: 80px;
  border-radius: 27px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 600;
  font-size: 14px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.send-button:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.send-button:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.is-loading {
  margin-right: 8px;
  vertical-align: middle;
  color: #667eea;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .deepseek-chat-container {
    padding: 10px;
    height: calc(100vh - 60px);
  }
  
  .chat-wrapper {
    max-height: none;
    height: 100%;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-header {
    padding: 16px 20px;
  }
  
  .chat-history {
    padding: 16px;
  }
  
  .chat-input-area {
    padding: 16px 20px;
  }
}

@media (max-width: 480px) {
  .deepseek-chat-container {
    padding: 5px;
  }
  
  .message-content {
    max-width: 90%;
    padding: 10px 12px;
  }
  
  .input-wrapper {
    gap: 8px;
  }
  
  .send-button {
    min-width: 60px;
    height: 48px;
  }
}
</style> 